package com.excilys.formation.projet.ebanking.webapp.flash;

import java.util.Enumeration;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class FlashScopeModifier {
	
	private static final FlashScopeModifier MODIFIER = new FlashScopeModifier();
	
	private FlashScopeModifier() {}
	
	public static FlashScopeModifier getFlashScopeModifier() {
		return MODIFIER;
	}
	
	public void put(ServletRequest request, String attributeName, Object attributeValue) {
		HttpServletRequest servletRequest = ((HttpServletRequest) request);
		HttpSession session = servletRequest.getSession();
		session.setAttribute(attributeName + ".flash", attributeValue);
	}
	
	public void get(ServletRequest request) {
		HttpServletRequest servletRequest = ((HttpServletRequest) request);
		HttpSession session = servletRequest.getSession();
		@SuppressWarnings("unchecked")
		Enumeration<String> enu = session.getAttributeNames();
		while (enu.hasMoreElements()) {
			String str = enu.nextElement();
			if (str.endsWith(".flash")) {
				request.setAttribute(str.replace(".flash", ""), session.getAttribute(str));
				session.removeAttribute(str);
			}
		}
		
	}
}
